<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-radio-group v-model="viewType" size="small" @input="onViewType">
						<el-radio-button label="list-view">
							<span class="el-icon-c-scale-to-original"></span>
							<span>列表</span>
						</el-radio-button>
						<el-radio-button label="chart-view">
							<span class="el-icon-s-data"></span>
							<span>图表</span>
						</el-radio-button>
					</el-radio-group>
				</div>
				<div class="flex-end-center-wrap">
					<el-date-picker
						v-model="searchParams.collectTime"
						:picker-options="pickerOptions"
						:disabled="onViewTypeNum === 1"
						format="yyyy-MM-dd HH:mm"
						type="datetimerange"
						clearable
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						size="small"
						style="width: 380px"
						class="item-gap"
						@change="onTimeChange"
					></el-date-picker>
					<jk-select v-model="searchParams.shiftId" clearable placeholder="班次" :disabled="onViewTypeNum === 1" :option-list="shiftList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onShiftListChange"></jk-select>
					<jk-search-input v-model="searchParams.machineNameOrCode" :disabled="onViewTypeNum === 1" placeholder="机台编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<component
				:is="viewType"
				:shift-name="searchParams.shiftName"
				:table-data="tableData"
				:height="tableHeight + 90"
				@getListRequest="getListRequest"
			></component>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatTime, formatDate } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { workforcemanagementShiftPage } from '../../../api/schedule/shift';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import {
        productionPrdGoldenFireAlarmRecordGetGoldenFireAlarmStatistics
    } from '../../../api/statistic/metalAndSparkAlarmStatistics';
    import detailDialog from './detail-dialog.vue';
    import listView from './components/list-view.vue';
    import chartView from './components/chart-view.vue';
    import { workforceManagementShiftGetByTime } from '@/api/schedule/shift';
    export default {
        name: 'MetalAndSparkAlarmStatistics',
        components: { detailDialog, listView, chartView },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                viewType: 'list-view',
                apiItem: {
                    'page': productionPrdGoldenFireAlarmRecordGetGoldenFireAlarmStatistics
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                processList: [],
                workshopList: [],
                tableLoading: true,
                tableData: [],
                totalCount: 0,
                shiftList: [],
                groupList: [],
                shiftGetByTime: {},
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    collectTime: null,
                    shiftId: null,
                    shiftName: null,
                    groupId: null,
                    processCode: '',
                    workshopId: null
                },
                onViewTypeNum: null
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            onViewType(e) {
                if (e === 'chart-view') {
                    this.onViewTypeNum = 1;
                    this.$set(this.searchParams, 'shiftName', this.shiftGetByTime.currentShiftInfo.name);
                    this.$set(this.searchParams, 'shiftId', this.shiftGetByTime.currentShiftInfo.id);
                    const staBelongTime = this.shiftGetByTime.currentShiftInfo.belongDate + ' ' + this.shiftGetByTime.currentShiftInfo.beginHour + ':' + '00';
                    const endBelongTime = this.shiftGetByTime.currentShiftInfo.belongDate + ' ' + this.shiftGetByTime.currentShiftInfo.endHour + ':' + '00';
                    this.searchParams.collectTime = [staBelongTime, endBelongTime];
                    this.getListRequest();
                } else {
                    this.onViewTypeNum = 5;
                }
            },
            onShiftListChange(e) {
                if (e === 30) {
                    // 白班
                    this.$set(this.searchParams, 'shiftName', '白班');
                    const staBelongTime = this.shiftGetByTime.currentShiftInfo.belongDate + ' ' + this.shiftGetByTime.currentShiftInfo.beginHour + ':' + '00';
                    const endBelongTime = this.shiftGetByTime.currentShiftInfo.belongDate + ' ' + this.shiftGetByTime.currentShiftInfo.endHour + ':' + '00';
                    this.searchParams.collectTime = [staBelongTime, endBelongTime];
                } else {
                    this.$set(this.searchParams, 'shiftName', '晚班');
                    const staBelongTime = this.shiftGetByTime.lastShiftInfo.belongDate + ' ' + this.shiftGetByTime.lastShiftInfo.beginHour + ':' + '00';
                    const endBelongTime = this.shiftGetByTime.lastShiftInfo.belongDate + ' ' + this.shiftGetByTime.lastShiftInfo.endHour + ':' + '00';
                    this.searchParams.collectTime = [staBelongTime, endBelongTime];
                }
            },
            // 当前班次信息
            getScheduleShift() {
                const params = {
                    belongTime: formatTime(Date.now()),
                    workshopId: 36
                };
                return workforceManagementShiftGetByTime(params).then(res => {
                    if (res.data.status === 200) {
                        this.shiftGetByTime = res.data.res || {};
                        this.$set(this.searchParams, 'shiftName', this.shiftGetByTime.currentShiftInfo.name);
                        this.$set(this.searchParams, 'shiftId', this.shiftGetByTime.currentShiftInfo.id);
                        const staBelongTime = this.shiftGetByTime.currentShiftInfo.belongDate + ' ' + this.shiftGetByTime.currentShiftInfo.beginHour + ':' + '00';
                        const endBelongTime = this.shiftGetByTime.currentShiftInfo.belongDate + ' ' + this.shiftGetByTime.currentShiftInfo.endHour + ':' + '00';
                        this.searchParams.collectTime = [staBelongTime, endBelongTime];
                    }
                });
            },
            onTimeChange(e) {
                this.$set(this.searchParams, 'shiftId', '');
                this.$set(this.searchParams, 'shiftName', '');
                if (this.searchParams.collectTime != null) {
                    const a = this.formatDate(e[0]);
                    const b = this.formatDate(e[1]);
                    this.searchParams.collectTime = [a, b];
                } else {
                    this.searchParams.collectTime = '';
                }
            },
            formatDate(dateString) {
                // 创建 Date 对象
                const date = new Date(dateString);

                // 提取年、月、日、时、分、秒
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的，所以需要加 1
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');

                // 构建新的日期字符串
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getShiftListRequest() {
                const params = {
                    auditState: 1,
                    workshopId: 36
                };
                return workforcemanagementShiftPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                        this.$set(this.searchParams, 'shiftId', this.shiftList && this.shiftList.length ? this.shiftList[0].id : null);
                    }
                });
            },
            getGroupListRequest() {
                return personnelGroupPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                // if (this.searchParams.collectTime === null) this.searchParams.collectTime = [formatTime(Date.now()), formatTime(Date.now())];
                if (this.searchParams.collectTime === null) this.searchParams.collectTime = ['2024-07-01 00:00:00', '2024-07-31 00:00:00'];
                // this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
                // this.processList = this.$store.state.user.userProcess.processList ? this.$store.state.user.userProcess.processList.filter(x => !['QH', 'TB', 'EB', 'MB'].includes(x.code.toUpperCase())) : [];
                // this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getGroupListRequest();
                await this.getShiftListRequest();
                await this.getScheduleShift();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            }
        }
    };
</script>
<style>
</style>
